<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择收款记录"
    width="1200"
    overflow
    @close="handleClose"
  >
    <vxe-table
      ref="xTable"
      border
      min-height="300"
      header-align="center"
      :column-config="{ resizable: true }"
      :data="TableData"
      size="small"
      :row-config="{ keyField: 'id' }"
      :radio-config="radioConfig"
      :show-footer="true"
      :footer-method="footerMethod"
      @checkbox-change="checkboxChange"
    >
      <vxe-column type="checkbox" width="60" />
      <vxe-column field="receiveDate" title="收款时间" width="120" />
      <vxe-column field="receiveType" :formatter="['valOfKey', OptionsFKFS]" title="收款方式" width="120" />
      <vxe-column field="nodeType" title="付款类型">
        <template v-slot:default="{ row }">
          {{
            row.nodeType === "0"
              ? "合同预收款"
              : row.nodeType === "1"
                ? "订单预收款"
                : row.nodeType === "2"
                  ? "实收款"
                  : ""
          }}
        </template>
      </vxe-column>
      <vxe-column field="receivePrice" title="收款金额" width="120" />
      <vxe-column
        field="orderPrePrice"
        title="含订单预收款（元）"
        width="150"
      />
      <vxe-column field="paymentPrice" title="已付金额" width="120" />
      <vxe-column field="notPaymentPrice" title="未付金额" width="120" />
      <vxe-column field="file" title="附件" width="120" />
      <vxe-column field="mark" title="内容以及用途" />
    </vxe-table>
    <vxe-pager
      v-model:current-page="tablePage.currentPage"
      v-model:page-size="tablePage.pageSize"
      :layouts="[
        'Sizes',
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'FullJump',
        'Total'
      ]"
      :total="tablePage.total"
      size="small"
      @page-change="handlePageChange"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" color="#1E3485" @click="go()">
          确认
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from "vue";
import { VxeTablePropTypes } from "vxe-table";
import { VxeTableInstance, VxePagerEvents, VxeTableEvents } from "vxe-table";

import { getreceivePaymenthistory } from "@/api/ERP_PaymentMange";

const emit = defineEmits(["close", "confirm"]);
// 弹窗关闭/打开事件
const props = defineProps({
  visible: Boolean,
  contractId: String,
  OptionsFKFS: {
    type: Array,
    default: () => [],
  },
});
function handleClose() {
  emit("close", false);
}
const dialogVisible = ref(false);
const formLabelWidth = "140px";

watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (props.contractId != "") {
      getlist();
    }
  },
  { immediate: true }
);
//表格
const TableData = ref([]);

const searchForm = ref({
  date: []
});
// 表格分页配置
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

//获取发票列表
const getlist = (query?: string) => {
  let params: any = {};
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  params.contractId = props.contractId;
  getreceivePaymenthistory(params).then((response: any) => {
    // if(!response.data) return
    TableData.value = response.data.map(v => {
      return {
        ...v,
        paymentPrice: v.paymentPrice || 0,
        notPaymentPrice: v.receivePrice - (v.paymentPrice || 0)
      }
    });
    tablePage.total = response.data.totalElements;
  });
};

const radioConfig = reactive<VxeTablePropTypes.RadioConfig>({
  checkRowKey: ""
});

// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getlist();
};
const tableRef = ref();
const selectRow = ref();
const selectAllChangeEvent: VxeTableEvents.CheckboxAll = ({ checked }) => {
  const $table = tableRef.value;
  if ($table) {
    selectRow.value = $table.getCheckboxRecords();
  }
};
const selectChangeEvent: VxeTableEvents.CheckboxChange = ({ checked }) => {
  const $table = tableRef.value;
  if ($table) {
    selectRow.value = $table.getCheckboxRecords();
  }
};
function go() {
  emit("close", selectedRows);
  dialogVisible.value = false;
}
// 清空按钮点击事件
const clearAllFields = () => {
  // 重置SearchForm对象的所有属性
  for (const key in searchForm) {
    if (searchForm.value.hasOwnProperty(key)) {
      if (key === "signDate") {
        // searchForm[key] = [];
        searchForm[key] = null;
      } else {
        searchForm[key] = "";
      }
    }
  }
};
const xTable = ref<VxeTableInstance>();
const selectedRows: any = [];
//勾选
function checkboxChange({ checked, row }) {
  if (checked) {
    selectedRows.push(row);
  } else {
    const index = selectedRows.findIndex(r => r.id === row.id);
    if (index > -1) {
      selectedRows.splice(index, 1);
    }
  }
  const $table = xTable.value;
  $table.updateFooter();
}
//合计行
function footerMethod({ columns, data }) {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "合计";
      }
      if (
        ["receivePrice", "orderPrePrice", "paymentPrice"].includes(column.field)
      ) {
        return sumNum(selectedRows, column.field);
      }
      return null;
    })
  ];
}
const sumNum = (list: any[], field: string) => {
  let count = 0;
  list.forEach(item => {
    count += Number(item[field]);
  });
  return count;
};
</script>
